package cz.byteworks.sandbox.html5.newsbox.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import cz.byteworks.sandbox.html5.newsbox.exception.ServiceException;
import cz.byteworks.sandbox.html5.newsbox.service.INewsService;

@WebServlet(urlPatterns = "/news", loadOnStartup = 0)
public class NewsBoxServlet extends BaseServlet {

    private static final long serialVersionUID = 5927505252008796347L;

    @Autowired(required = true)
    private INewsService newsService;

    private String lastMessagesJSON = "";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // headers
        resp.setHeader("Content-Type", "text/event-stream");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setCharacterEncoding("UTF-8");

        // write output
        try {
            String messagesJSON = newsService.getUnreadMessagesJSONArray();
            if (messagesJSON != null) {
                lastMessagesJSON = messagesJSON;
            }
            resp.getWriter().println("event: message\n");
            resp.getWriter().println("data: " + lastMessagesJSON+"\n\n");
        } catch (ServiceException e) {
            resp.getWriter().println("error:" + e.getMessage());
        }
    }

}
